package io.renren.modules.newBackground.shanDongCmcc.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.OkHttp3Util;
import io.renren.common.utils.Result;
import io.renren.commons.dynamic.datasource.annotation.DataSource;
import io.renren.modules.lucky.entity.PhoneLocationEntity;
import io.renren.modules.lucky.service.PhoneLocationService;
import io.renren.modules.newBackground.shanDongCmcc.config.ShanDongCmccConfig;
import io.renren.modules.newBackground.shanDongCmcc.config.ShanDongCmccRSA;
import io.renren.modules.newBackground.shanDongCmcc.dto.*;
import io.renren.modules.wap.entity.ExternalConfigEntity;
import io.renren.modules.wap.entity.ExternalOrdersComplainEntity;
import io.renren.modules.wap.entity.ExternalOrdersEntity;
import io.renren.modules.wap.service.ExternalConfigService;
import io.renren.modules.wap.service.ExternalOrdersComplainService;
import io.renren.modules.wap.service.ExternalOrdersService;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@DataSource("wap")
public class ShanDongCmccBackGroundServiceImpl implements ShanDongCmccBackGroundService {

    private static final Logger logger = LoggerFactory.getLogger(ShanDongCmccBackGroundServiceImpl.class);

    private static final String APP_ID = "shandong-cmcc";
    private static final String COMPLAIN_URL = "https://m.sd.10086.cn/zapi/h5_business/orderMangerPacke/qryOrderComplaint";

    private static final String UNSUBSCRIBE_URL = "https://m.sd.10086.cn/zapi/h5_business/orderMangerPacke/unsubscribe";

    @Autowired
    private ExternalConfigService externalConfigService;

    @Autowired
    private ExternalOrdersComplainService externalOrdersComplainService;

    @Autowired
    private ExternalOrdersService externalOrdersService;


    @Override
    public Result queryComplain(ShanDongCmccBackGroundReq backGroundReq) {

        ExternalConfigEntity externalConfig = externalConfigService.getConfigByQueryId(APP_ID);
        if (externalConfig == null) {
            logger.error("山东移动后台接口配置不存在");
            return new Result().error("山东移动后台接口配置不存在");
        }
        ShanDongCmccConfig shanDongCmccConfig = JSON.parseObject(externalConfig.getConfigInfo(), ShanDongCmccConfig.class);
        String channelCode = shanDongCmccConfig.getChannelCode();
        String date = DateUtils.coverDate(backGroundReq.getTime());

        String dataStr = date + "_" + channelCode;
        String sign = ShanDongCmccRSA.sign(dataStr, shanDongCmccConfig.getPrivateKey());
        ShanDongCmccComplainReq backGroundComplainReq = new ShanDongCmccComplainReq();
        backGroundComplainReq.setTime(date);
        backGroundComplainReq.setSign(sign);
        backGroundComplainReq.setChannelCode(channelCode);


        try {
            logger.info("山东移动 后台查询投诉 入参：{}", JSON.toJSONString(backGroundComplainReq));
            String respStr = OkHttp3Util.postByJson(COMPLAIN_URL, backGroundComplainReq, null);
            logger.info("山东移动 后台查询投诉 返回：{}", respStr);
            ShanDongCmccComplainResp resp = JSON.parseObject(respStr, ShanDongCmccComplainResp.class);
            if (ObjectUtil.isNotEmpty(resp)) {
                ShanDongCmccComplainResp.DataNode dataNode = resp.getData();
                List<ExternalOrdersComplainEntity> complainList = Lists.newArrayList();

                List<ExternalOrdersComplainEntity> updateList = Lists.newArrayList();
                if (ObjectUtil.isNotEmpty(dataNode) && dataNode.getTotal() > 0) {
                    //循环处理
                    for (ShanDongCmccComplainResp.OrderInfo orderInfo : dataNode.getOrderInfo()) {
                        String orderNo = orderInfo.getOrderId();
                        // 查询订单是否存在
                        ExternalOrdersEntity externalOrdersEntity = externalOrdersService.getByOrderNo(orderNo);
                        if (ObjectUtil.isEmpty(externalOrdersEntity)) {
                            logger.error("山东移动 后台查询投诉 订单不存在：{}", orderNo);
                            continue;
                        }
                        //是否已有
                        ExternalOrdersComplainEntity complainEntity = externalOrdersComplainService.getByOrderNo(orderNo);
                        if (ObjectUtil.isNotEmpty(complainEntity)) {
                            if (StrUtil.isNotBlank(complainEntity.getRecNo())) {
                                // 已有投诉记录
                                continue;
                            } else {
                                complainEntity.setRecNo(orderInfo.getRecNo());
                                complainEntity.setSerialNo(orderInfo.getSerialNo());
                                complainEntity.setComplainTime(backGroundReq.getTime());
                                updateList.add(complainEntity);
                            }
                        } else {
                            //存入投诉表
                            ExternalOrdersComplainEntity externalOrdersComplainEntity = new ExternalOrdersComplainEntity();

                            externalOrdersComplainEntity.setOrderNo(orderNo);
                            externalOrdersComplainEntity.setPhone(externalOrdersEntity.getPhone());
                            externalOrdersComplainEntity.setComplainTime(backGroundReq.getTime());
                            externalOrdersComplainEntity.setRecNo(orderInfo.getRecNo());
                            externalOrdersComplainEntity.setSerialNo(orderInfo.getSerialNo());
                            externalOrdersComplainEntity.setGoodsId(externalOrdersEntity.getGoodsId());
                            externalOrdersComplainEntity.setGoodsName(externalOrdersEntity.getGoodsName());
                            externalOrdersComplainEntity.setAppId(APP_ID);
                            externalOrdersComplainEntity.setStatus(1);

                            complainList.add(externalOrdersComplainEntity);
                        }
                    }
                    //批量插入
                    if (CollUtil.isNotEmpty(complainList)) {
                        externalOrdersComplainService.insertBatch(complainList);
                    }
                    //批量更新
                    if (CollUtil.isNotEmpty(updateList)) {
                        externalOrdersComplainService.updateBatchById(updateList);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("{} 山东移动 后台查询投诉 异常", e);
            return new Result().error("系统异常，稍后再试");
        }
        return new Result().ok("ok");
    }


    /**
     * 查询退订接口
     */
    @Override
    public Result queryUnsubscribe(ShanDongCmccBackGroundReq backGroundReq) {
        ExternalConfigEntity externalConfig = externalConfigService.getConfigByQueryId(APP_ID);
        if (externalConfig == null) {
            logger.error("山东移动后台接口配置不存在");
            return new Result().error("山东移动后台接口配置不存在");
        }
        ShanDongCmccConfig shanDongCmccConfig = JSON.parseObject(externalConfig.getConfigInfo(), ShanDongCmccConfig.class);
        String channelCode = shanDongCmccConfig.getChannelCode();
        String date = DateUtils.coverDate(backGroundReq.getTime());

        String dataStr = date + "_" + channelCode;
        String sign = ShanDongCmccRSA.sign(dataStr, shanDongCmccConfig.getPrivateKey());

        ShanDongCmccUnsubscribeReq unsubscribeReq = new ShanDongCmccUnsubscribeReq();
        unsubscribeReq.setOpTime(date);
        unsubscribeReq.setSign(sign);
        unsubscribeReq.setChannelCode(channelCode);

        try {
            logger.info("山东移动 后台查询退订 入参：{}", JSON.toJSONString(unsubscribeReq));
            String respStr = OkHttp3Util.postByJson(UNSUBSCRIBE_URL, unsubscribeReq, null);
            logger.info("山东移动 后台查询退订 返回：{}", respStr);
            ShanDongCmccUnsubscribeResp resp = JSON.parseObject(respStr, ShanDongCmccUnsubscribeResp.class);
            if (ObjectUtil.isNotEmpty(resp)) {
                ShanDongCmccUnsubscribeResp.DataNode dataNode = resp.getData();
                List<ExternalOrdersComplainEntity> complainList = Lists.newArrayList();

                List<ExternalOrdersComplainEntity> updateList = Lists.newArrayList();
                if (ObjectUtil.isNotEmpty(dataNode) && dataNode.getTotal() > 0) {
                    //循环处理
                    for (ShanDongCmccUnsubscribeResp.CancellationInfo orderInfo : dataNode.getOrderInfo()) {
                        String orderNo = orderInfo.getOrderId();
                        //查询是否有投诉记录
                        ExternalOrdersComplainEntity complainEntity = externalOrdersComplainService.getByOrderNo(orderNo);
                        if (ObjectUtil.isNotEmpty(complainEntity)) {
                            //更新状态
                            complainEntity.setStatus(99);
                            complainEntity.setCancelOid(orderInfo.getCanceloId());
                            complainEntity.setCancelOrderId(orderInfo.getOrderNo());
                            complainEntity.setCancelTime(orderInfo.getRecdate());
                            updateList.add(complainEntity);
                        } else {
                            // 查询订单是否存在
                            ExternalOrdersEntity externalOrdersEntity = externalOrdersService.getByOrderNo(orderNo);
                            if (ObjectUtil.isEmpty(externalOrdersEntity)) {
                                logger.error("山东移动 后台查询退订 订单不存在：{}", orderNo);
                                continue;
                            }
                            //存入投诉表
                            ExternalOrdersComplainEntity externalOrdersComplainEntity = new ExternalOrdersComplainEntity();

                            externalOrdersComplainEntity.setOrderNo(orderNo);
                            externalOrdersComplainEntity.setPhone(externalOrdersEntity.getPhone());
                            externalOrdersComplainEntity.setCancelOid(orderInfo.getCanceloId());
                            externalOrdersComplainEntity.setCancelOrderId(orderInfo.getOrderNo());
                            externalOrdersComplainEntity.setCancelTime(orderInfo.getRecdate());
                            externalOrdersComplainEntity.setGoodsId(externalOrdersEntity.getGoodsId());
                            externalOrdersComplainEntity.setGoodsName(externalOrdersEntity.getGoodsName());
                            externalOrdersComplainEntity.setAppId(APP_ID);
                            externalOrdersComplainEntity.setStatus(99);

                            complainList.add(externalOrdersComplainEntity);
                        }


                    }
                    //批量插入
                    if (CollUtil.isNotEmpty(complainList)) {
                        externalOrdersComplainService.insertBatch(complainList);
                    }
                    //批量更新
                    if (CollUtil.isNotEmpty(updateList)) {
                        externalOrdersComplainService.updateBatchById(updateList);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("{} 山东移动 后台查询退订 异常", e);
            return new Result().error("系统异常，稍后再试");
        }

        return new Result().ok("ok");
    }
}
